import axios from 'axios'
import mt from 'moment'
import 'moment/locale/zh-cn'
import qs from 'querystring'
import {Toast, Modal} from 'antd-mobile'
const nodeUrl = require('url')

mt.locale('zh-cn')
export const moment = mt

const defaultAxiosConf = {
  timeout: 15000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  baseURL: '/api'
}

export function http(params = {}, fn) {
  if (typeof fn === 'function') fn(true)
  if (params.data && !(params.data instanceof FormData)) params.data = qs.stringify(params.data)
  if (!params.method) params.method = 'get'
  if (params.method.toLowerCase() === 'get') params.url += `?${qs.stringify(params.data)}`
  return axios({...defaultAxiosConf, ...params}).then(res => {
    if (typeof fn === 'function') fn(false)
    if (res.data.result === 0) throw new Error(res.data.mes)
    return res.data
  }).catch(err => {
    if (typeof fn === 'function') fn(false)
    const {tip = true} = params
    if (tip) Toast.info(String(err.message || '网络异常'))
    throw err
  })
}

export const post = (url, params = {}, fn, tip = true) => http({method: 'post', data: params, url, tip}, fn)

export const get = (url, params = {}, fn, tip = true) => http({method: 'get', data: params, url, tip}, fn)

export function upload(url, form, params, fn, cb) {
  if (params) {
    url = `${url}?${qs.stringify(params)}`
  }
  return http({
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data;'
    },
    url: url,
    data: form,
    onUploadProgress(processEvent) {
      // 原生进度事件
      const percent = processEvent.loaded / processEvent.total * 100
      if (typeof cb === 'function') cb(percent)
    }
  }, fn)
}

export const modal = {
  alert(content) {
    return new Promise((resolve, reject) => {
      Modal.alert('提示', content, [
        { text: '确定', onPress: () => resolve() }
      ])
    })
  },
  confirm(content) {
    return new Promise((resolve, reject) => {
      Modal.alert('提示', content, [
        { text: '取消', onPress: () => reject() },
        { text: '确定', onPress: () => resolve() }
      ])
    })
  },
  loading(boo) {
    boo ? Toast.loading('loading...', 0) : Toast.hide()
  },
  toast(content) {
    Toast.info(content, 3)
  },
  prompt({ title, message, defaultValue, placeholders, type = 'default', promise }) {
    return new Promise((resolve, reject) => {
      Modal.prompt(title, message, [{
        text: '取消',  onPress: () => {
          reject()
        }}, {
        text: '确定', onPress: value => {
          return promise ? promise(value) : resolve(value)
        }}], type, defaultValue, placeholders)
    })
  }
}

export function debounce(func, delay = 300) {
  let timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func(...args)
    }, delay)
  }
}

export function addClass(className, newClass) {
  return className
    ? className
      .split(/\s+/)
      .filter(name => name !== newClass)
      .concat(newClass)
      .join(' ')
    : newClass
}

// 解析query
export function queryParse (str) {
  if (typeof str === 'undefined') str = window.location.href
  if (typeof str !== 'string') return {}
  const search = nodeUrl.parse(str).search
  if (search) {
    return qs.parse(search.substr(1))
  } else {
    return {}
  }
}
